<template>
  <div class="login-container">
    <!-- 背景层 -->
    <div class="background-layer"></div>

    <!-- 毛玻璃效果卡片 -->
    <transition name="fade-transform" mode="out-in">
      <div class="glass-card" :key="activeName">
        <div class="brand-wrapper">
          <div class="logo"></div>
          <h1 class="brand-title">心语</h1>
          <div class="brand-subtitle">让心灵遇见更好的自己</div>
        </div>

        <el-tabs
            v-model="activeName"
            stretch
            class="auth-tabs"
            @tab-click="handleTabClick"
        >
          <!-- 登录面板 -->
          <el-tab-pane name="1">
            <template #label>
              <span class="custom-tab-label">
                <svg-icon icon-class="login" class="tab-icon"/> 用户登录
              </span>
            </template>
            <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
              <el-form-item prop="username">
                <el-input
                    v-model="loginForm.username"
                    type="text"
                    size="default"
                    auto-complete="off"
                    placeholder="账号"
                >
                  <template #prefix>
                    <svg-icon icon-class="user" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    v-model="loginForm.password"
                    type="password"
                    size="default"
                    auto-complete="off"
                    placeholder="密码"
                    @keyup.enter="handleLogin"
                >
                  <template #prefix>
                    <svg-icon icon-class="password" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled" style="display: flex; align-items: center; gap: 8px">
                <el-input
                    v-model="loginForm.code"
                    size="default"
                    auto-complete="off"
                    placeholder="验证码"
                    style="flex: 1"
                    @keyup.enter="handleLogin"
                >
                  <template #prefix>
                    <svg-icon icon-class="validCode" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
                <div class="login-code" style="flex-shrink: 0">
                  <img :src="codeUrl" @click="getCode" class="login-code-img" style="height: 40px">
                </div>
              </el-form-item>
              <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
              <el-form-item style="width:100%;">
                <el-button
                    :loading="loading"
                    size="default"
                    type="primary"
                    style="width:100%;"
                    @click.prevent="handleLogin"
                >
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
                <!--<div style="float: right;" v-if="register">
                  <router-link class="link-type" :to="'/register'">立即注册</router-link>
                </div>-->
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 注册面板 -->
          <!--<el-tab-pane name="2">
            <template #label>
              <span class="custom-tab-label">
                <svg-icon icon-class="register" class="tab-icon"/> 新用户注册
              </span>
            </template>
            <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
              <el-form-item prop="username">
                <el-input
                    v-model="registerForm.username"
                    type="text"
                    size="default"
                    auto-complete="off"
                    placeholder="账号"
                >
                  <template #prefix>
                    <svg-icon icon-class="user" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    v-model="registerForm.password"
                    type="password"
                    size="default"
                    auto-complete="off"
                    placeholder="密码"
                    @keyup.enter="handleRegister"
                >
                  <template #prefix>
                    <svg-icon icon-class="password" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    size="default"
                    auto-complete="off"
                    placeholder="确认密码"
                    @keyup.enter="handleRegister"
                >
                  <template #prefix>
                    <svg-icon icon-class="password" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled"  style="display: flex; align-items: center; gap: 8px">
                <el-input
                    size="default"
                    v-model="registerForm.code"
                    auto-complete="off"
                    placeholder="验证码"
                    style="flex: 1"
                    @keyup.enter="handleRegister"
                >
                  <template #prefix>
                    <svg-icon icon-class="validCode" class="el-input__icon input-icon"/>
                  </template>
                </el-input>
                <div class="login-code" style="flex-shrink: 0">
                  <img :src="codeUrl" @click="getCode" class="login-code-img" style="height: 40px">
                </div>
              </el-form-item>
              <el-form-item style="width:100%;">
                <el-button
                    :loading="loading"
                    size="default"
                    type="primary"
                    style="width:100%;"
                    @click.prevent="handleRegister"
                >
                  <span v-if="!loading">注 册</span>
                  <span v-else>注 册 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>-->
        </el-tabs>
      </div>
    </transition>

    <!-- 装饰粒子 -->
    <div class="particles">
      <div class="particle" v-for="(n,index) in 30" :key="index"></div>
    </div>
  </div>
</template>

<script setup>
import {getCodeImg, register} from "@/api/login";
import Cookies from "js-cookie";
import {encrypt, decrypt} from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import {useRoute, useRouter} from "vue-router";

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();
const activeName = ref('1');

const loginForm = ref({
  username: "admin",
  password: "123456",
  rememberMe: false,
  code: "",
  uuid: ""
});


const loginRules = {
  username: [{required: true, trigger: "blur", message: "请输入您的账号"}],
  password: [{required: true, trigger: "blur", message: "请输入您的密码"}],
  code: [{required: true, trigger: "change", message: "请输入验证码"}],
};


const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const isRegister = ref(false);
const redirect = ref(undefined);

const handleTabClick = (tab) => {
  console.log(`切换到 ${tab.props.label} 面板`);
  activeName.value = tab.paneName;
  if (tab.paneName === '1') {
    proxy.$refs.loginRef?.resetFields();
  } else {
    proxy.$refs.registerRef?.resetFields();
  }
};

// 监听路由变化，如果路由带了 redirect 参数，则设置重定向地址
watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, {immediate: true});

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, {expires: 30});
        Cookies.set("password", encrypt(loginForm.value.password), {expires: 30});
        Cookies.set("rememberMe", loginForm.value.rememberMe, {expires: 30});
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({path: redirect.value || "/", query: otherQueryParams});
        // 跳转后清空表单和验证码,延迟一秒执行
        setTimeout(() => {
          loginForm.value = {};
          registerForm.value = {};
        }, 1000)
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

// -----------------------------------注册-----------------------------
import {ElMessageBox} from "element-plus";
import {ref} from "vue";

const registerForm = ref({
  username: "",
  password: "",
  confirmPassword: "",
  code: "",
  uuid: ""
});

const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    {required: true, trigger: "blur", message: "请输入您的账号"},
    {min: 2, max: 20, message: "用户账号长度必须介于 2 和 20 之间", trigger: "blur"}
  ],
  password: [
    {required: true, trigger: "blur", message: "请输入您的密码"},
    {min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur"}
  ],
  confirmPassword: [
    {required: true, trigger: "blur", message: "请再次输入您的密码"},
    {required: true, validator: equalToPassword, trigger: "blur"}
  ],
  code: [{required: true, trigger: "change", message: "请输入验证码"}]
};

function handleRegister() {
  proxy.$refs.registerRef.validate(valid => {
    if (valid) {
      loading.value = true;
      register(registerForm.value).then(res => {
        const username = registerForm.value.username;
        ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", "系统提示", {
          dangerouslyUseHTMLString: true,
          type: "success",
        }).then(() => {
          activeName.value = "1";
          loading.value = false;
        }).catch(() => {
        });
      }).catch(() => {
        loading.value = false;
        if (captchaEnabled) {
          getCode();
        }
      });
    }
  });
}

onMounted(() => {
  getCode();
  getCookie();
  activeName.value = proxy.$route.query.query || "1";
})

</script>

<style lang="scss" scoped>
:deep(.el-input) {
  --el-input-height: 40px; // 调整输入框高度为40px
  --el-input-icon-size: 18px; // 调整图标尺寸

  .el-input__wrapper {
    padding: 0 12px; // 调整内边距
  }

  .el-input__inner {
    height: var(--el-input-height);
    line-height: var(--el-input-height); // 保持文字垂直居中
    font-size: 14px; // 适当缩小字体
  }

  .input-icon {
    margin-top: -2px; // 微调图标位置
  }
}
.login-code-img, .register-code-img {
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid #eee;
  height: 40px !important; // 保持与输入框同高
  width: auto; // 保持图片原始比例
}

.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .glass-card {
    position: relative;
    width: 480px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    margin-top: -50px; // 垂直居中微调
    z-index: 2; // 确保在粒子层之上
  }

  .particles {
    z-index: 1; // 确保在卡片之下
  }
}
.login-container {
  position: relative;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  &::before {
    content: '';
    position: absolute;
    width: 150%;
    height: 150%;
    //background-image: url('../assets/images/psy-pattern.png');
    opacity: 0.1;
    animation: grain 8s steps(10) infinite;
  }
}

.background-layer {
  position: absolute;
  width: 100%;
  height: 100%;
  //background: url('../assets/images/psy-bg.jpg') center/cover;
  filter: blur(2px);
}

.glass-card {
  position: relative;
  width: 480px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  transform: translateY(-5%);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 20px;
    background: linear-gradient(120deg,
        rgba(255, 255, 255, 0.2) 0%,
        rgba(255, 255, 255, 0.05) 100%);
    z-index: -1;
  }
}

.brand-wrapper {
  text-align: center;
  margin-bottom: 40px;

  .logo {
    width: 80px;
    height: 80px;
    margin: 0 auto 20px;
    //background: url('../assets/images/psy-logo.png') center/contain;
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
  }

  .brand-title {
    font-size: 24px;
    color: #2c3e50;
    letter-spacing: 2px;
    margin-bottom: 8px;
    font-weight: bolder;
  }

  .brand-subtitle {
    font-size: 14px;
    color: #7f8c8d;
    letter-spacing: 1px;
  }
}

.auth-tabs {
  :deep(.el-tabs__nav-wrap::after) {
    background-color: transparent;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    color: #95a5a6 !important;
    transition: all 0.3s;

    &.is-active {
      color: #3498db !important;
    }
  }

  :deep(.el-tabs__active-bar) {
    background: #3498db;
    height: 3px;
  }
}

.custom-tab-label {
  display: flex;
  align-items: center;
  padding: 0 20px;

  .tab-icon {
    margin-right: 8px;
    font-size: 18px;
    transition: transform 0.3s;
  }

  &:hover .tab-icon {
    transform: translateY(-2px);
  }
}

.particles {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;

  .particle {
    position: absolute;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 50%;
    animation: float 15s infinite linear;

    @for $i from 1 through 30 {
      &:nth-child(#{$i}) {
        $size: random(8) + 2 + px;
        width: $size;
        height: $size;
        top: random(100) + 1%;
        left: random(100) + 1%;
        animation-delay: random(15) + s;
      }
    }
  }
}

@keyframes grain {
  0%, 100% {
    transform: translate(0, 0)
  }
  10% {
    transform: translate(-5%, -10%)
  }
  30% {
    transform: translate(3%, -15%)
  }
  50% {
    transform: translate(12%, 9%)
  }
  70% {
    transform: translate(9%, 4%)
  }
  90% {
    transform: translate(-1%, 7%)
  }
}

@keyframes float {
  0% {
    transform: translateY(0) scale(1);
    opacity: 0.6
  }
  50% {
    transform: translateY(-100px) scale(0.8);
    opacity: 0.3
  }
  100% {
    transform: translateY(-200px) scale(0.5);
    opacity: 0
  }
}

.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 优化表单元素样式 */
:deep(.el-input__inner) {
  // 完全透明背景与无边框
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;

  // 调整内边距使文字对齐
  padding-left: 32px !important;
  padding-right: 12px !important;

  // 文字样式强化
  font-weight: 500;
  color: #2c3e50 !important;

  // 移除所有状态下的边框
  &:hover, &:focus {
    border: none !important;
    box-shadow: none !important;
  }
}

:deep(.el-form-item__content) {
  // 移除多余的外边框
  box-shadow: none !important;
  border: none !important;
  background: transparent !important;
}

/* 移除验证码输入框的特殊样式 */
:deep(.el-form-item--large) {
  .el-form-item__content {
    border: none !important;
    box-shadow: none !important;
  }
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #3498db, #2980b9);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
  }
}
</style>
